<?php
namespace app\index\controller;

//load_trait('brximl/brx');
//  首页号航
//use think\Controller;-
use think\Request;
use think\Session;
use think\Loader;
use think\Db;
class Project extends \think\Controller
{
    use \traits\brximl\brx;
    /*****************************************************首页************************************************************************/
    public function index()
    {
        $this->rightInfo();
        isset($_GET['uid']) or die('非法地址请求！');
        $this->brxStart();
        $this->useFrontFk();
        $uid = isset($_GET['uid'])? $_GET['uid']:'';
        if($uid){
            $this->indexCententer($uid,$prj);
            if(!is_object($prj)) die('页面传递参数无效！');
        }
        $this->loadScript([
            'title'=>'TeCener-'.$prj->pro_name,'js'=>['TeC','project/index'],'css'=>['project/index']
        ]);
        //debugOut(request());
        $prjArr = $prj->toArray();
        $prjArr['oldVersion'] = $this->dyUrl('Doeeking','/index.php/Conero/Index/project.html');
        $this->assign('prj',$prjArr);
        return $this->fetch('index');
    }
    //  Index 内容生成器
    private function indexCententer($uid,&$prj)
    {
        $list = Loader::model('Plist');
        $prj = $list->get($uid);
        $uInfo = $this->infoUser();
              
        //debugOut($data);
        // 开发者
        $dev = Loader::model('Pdev');

        $isFounder = $dev->where(['pro_code'=>$uid,'user_code'=>$uInfo['user_code'],'founder_mk'=>'Y'])->count();
        $isFounder = $isFounder? true:false;

        $devArr = [];
        $devCt = $dev->where('pro_code',$uid)->count();         
        $devArr['count'] = $devCt;
        $data = $dev->where('pro_code',$uid)->limit(10)->order('edittm','asc')->select();        
        $xhtml = '';
        $i = 1;
        foreach($data as $v){
            $xhtml .= '<tr><td>'.$i.'</td><td>'.$v->name.'</td><td>'.$v->position.'</td><td>'.$v->start_dt.'</td><td>'.$v->editor.'</td><td>'.($isFounder || $uInfo['user_code'] == $v->user_code? '<a href="javascript:void(0);" onClick="TeC.MainTo(\'/TeCenter/index/project/paction/dev/'.$v->no.'.html?uid=conero\')">修改</a>':'').($isFounder? ',<a href="javascript:void(0)" id="dev_delete_btn">删除</a>':'').'</td></tr>';
            $i++;
        }
        if(empty($xhtml)){
            // 初次进入为空时自动插入编辑者            
            $dev->data([
                'pro_code'=>$uid,'user_code'=>$uInfo['user_code'],'name'=>$uInfo['user_name'],'position'=>'成员,创始人','start_dt'=>date('Y-m-d H:i:s'),'editor'=>$uInfo['user_name'],'founder_mk'=>'Y','edittm'=>date('Y-m-d H:i:s')
            ]);
            $res = $dev->save();
            $xhtml = '<tr><td colspan="4"><div class="alert alert-danger" role="alert"><strong>提示：</strong> 本项目还未添加任何开发者</div></td></tr>';
            if($res) $xhtml .= '<tr><td colspan="4"><div class="alert alert-success" role="alert"><strong>恭喜：</strong> 您已经成功登记到为开发者！刷新查看-</div></td></tr>'; 
        }
        $devArr['trs'] = $xhtml;
        $devArr['formurl'] = '/TeCenter/index/project/paction/dev.html?uid='.$uid;
        $devArr['isFounder'] = $isFounder? 'Y':'N';
        $this->assign('dev',$devArr);
        // 结构树
        $tree = Loader::model('Ptree');
        $treeCt = $tree->where('pro_code',$uid)->count();
        $treeArr = [];
        $treeArr['count'] = $treeCt;
        if($treeCt>0){
            $treeArr['content'] = '<iframe src="/Tecenter/index/project/branch.html?uid='.$uid.'" id="tree-branch"></iframe>
            ';
        }
        $treeArr['formurl'] = '/TeCenter/index/project/paction/tree.html?uid='.$uid;
        $this->assign('tree',$treeArr);
        // 日志表
        $log = Loader::model('Plogs');
        $logCt = $log->where('pro_code',$uid)->count();
        $logArr = [];
        $logArr['count'] = $logCt;
        $ctt = $this->_getLogs($uid,$logCt);
        if($ctt) $logArr['content'] = $ctt;
        $logArr['formurl'] = '/TeCenter/index/project/paction/log.html?uid='.$uid;
        $this->assign('log',$logArr);
    }
    // 日志列表   所需参数// $uid = pro_code;
    private function _getLogs($uid,$count=null,$page=1,$num=15)
    {
        $data = Db::table('project_logs')
            ->where('pro_code',$uid)
            ->page($page,$num)
            ->order('edittm desc')
            ->select();
        if(empty($count)) $count = Db::table('project_logs')->where('pro_code',$uid)->count();
        //debugOut(Db::table('project_logs')->where('pro_code',$uid)->paginate(10));// 系统提供的分页机制
        $xhtml = '';
        $i = 1;
        foreach($data as $v){
            $id = $v['log_no'];
            $xhtml .= '<tr><td>'.$i.'</td><td>'.$v['title'].'</td><td>'.$v['node_desc'].'</td><td>'.$v['spend_hours'].'</td><td>'.$v['edittm'].'</td><td>'.$v['dever_name'].'</td><td><a href="javascript:TeC.MainTo(\'/TeCenter/index/project/paction/log/'.$id.'.html?uid='.$v['pro_code'].'\');">修改</a>，<a href="javascript:TeC.deleteBtn(\'Plogs\',\''.$id.'\');">删除</a></td></tr>';
            $i++;
        }
        if($xhtml){
            $xhtml = '<table class="table table-striped">
                <tr><th>#</th><th>标题</th><th>节点名称</th><th>耗时</th><th>日期</th><th>编辑者</th><th>操作</th></tr>
                '.$xhtml.'
                </table>
            ';
        }
        // 分页
        $phtml = $this->getPageBar($page,$count,$num);
        if($phtml && $xhtml) $xhtml .= '<p class="page_bar">'.$phtml.'</p>';
        return $xhtml;
    }
    /*****************************************************项目数据处理************************************************************************/
    public function paction()
    {
        $uid = isset($_GET['uid'])? $_GET['uid']:'';
        $vtpl = getUrlBind('paction');
        switch($vtpl){
            case 'list':// 项目操作表单
                if($uid){
                    $list = Loader::model('Plist');
                    $prj = $list->get($uid);
                    $data = $prj->toArray();
                    $this->assign('list',$data);
                }                
                break;
            case 'dev':// 开发者
                $this->loadScript([
                    'js'=>['TeC','project/dev'],'css'=>['project/dev']
                ]);
                $no = getUrlBind('dev');
                $dev = [];
                $dev['pro_code'] = $_GET['uid'];
                if($no){
                    $db = Loader::model('Pdev');
                    $dbobj = $db->get($no);
                    $dev = $dbobj->toArray();
                }
                $dev['user_select'] = user_select();
                $this->assign('dev',$dev);
                break;
            case 'log':
                $id = getUrlBind('log');
                $logArr = ['pro_code'=>$_GET['uid']];
                if($id){
                    $db = Loader::model('Plogs');
                    $logArr = $db->get($id)->toArray();
                }
                $this->assign('logs',$logArr);
                break;
        }
        return $this->fetch($vtpl);
    }    
    /*****************************************************结构树************************************************************************/
    public function branch()
    {
        isset($_GET['uid']) or die('非法地址请求！');
        $this->brxStart();
        $this->useFrontFk();
        $uid = isset($_GET['uid'])? $_GET['uid']:'';
        $map = 'pro_code="'.$uid.'"';
        $pno = isset($_GET['pno'])? $_GET['pno']:'';
        $map .= ' and parents_node'.($pno? '="'.$pno.'"':' is null');
        $data = Db::table('project_tree')
            ->where($map)
            ->select();
        //debugOut($data);
        $tree = [];
        //  项目位置
        if($map){
            $tree['position'] = $this->_branchPosition($pno);
        }
        $xhtml = '';
        foreach($data as $v){
            $xhtml .= '<li class="list-group-item"><a href="/Tecenter/index/project/branch.html?uid='.$uid.'&pno='.$v['no'].'">'.$v['node_name'].'>></a></li>';
        }
        if($xhtml){
            $xhtml = '<ul class="list-group">'.$xhtml.'</ul>';
            $tree['lists'] = $xhtml;
            $xhtml = '';
        }
        $this->assign('tree',$tree);
        return $this->fetch('branch');
    }
    //  递归分支的配置标签
    private function _branchPosition($pno,$href='')
    {
        $xhtml = '';
        $map = 'no="'.$pno.'"';
        $data = Db::table('project_tree')->where($map)->find();
        if($data){
            $pno = $data['parents_node']? $data['parents_node']:'';
            $href = '';
            if($pno){
                $xhtml = $this->_branchPosition($pno);
                $href = '/Tecenter/index/project/branch.html?uid='.$data['pro_code'].'&pno='.$pno;
            }
            else $href = '/Tecenter/index/project/branch.html?uid='.$data['pro_code'];
            $xhtml .= '<a href="'.$href.'">'.$data['node_name'].'</a>/';
        }
        //debugOut($data);
        return $xhtml;
    }
    /*****************************************************表单处理************************************************************************/
    public function form()
    {
        $data = $_POST;
        $dataid = $data['dataid'];
        $m = Loader::model($dataid);
        if($dataid == 'Plist'){            
            //return json($data);
            if(isset($data['pk'])){//修改
                $map = ['pro_code'=>$data['pk']];unset($data['pk']);                
                $num = $m->save($data,$map);                
                if($num) return getSuccessTip([
                    'title'=>'数据修改',
                    'remark'=>'项目'.$data['pro_code'].'#'.$data['pro_name'].'已经被成功修改数据！'
                ]);
                else return getFailureTip([
                    'title'=>'数据修改',
                    'remark'=>'十分遗憾，项目'.$data['pro_code'].'#'.$data['pro_name'].'数据修改失败！'
                ]);
            }else{
                $uInfo = $this->infoUser();
                $data['user_code'] = $uInfo['user_code'];
                $data['editor'] = $uInfo['user_name'];
                $data['edittm'] = date('Y-m-d H:i:s');
                $data['environment'] = nl2br($data['environment']);
                $data['content'] = nl2br($data['content']);
                $m->data($data);       
                $num = $m->save();
                // 同步写写入成员
                if($num){
                    $dev = Loader::model('Pdev');
                    $dev->data([
                        'pro_code'=>$data['pro_code'],'user_code'=>$uInfo['user_code'],'name'=>$uInfo['user_name'],'position'=>'成员,创始人','start_dt'=>date('Y-m-d H:i:s'),'editor'=>$uInfo['user_name'],'founder_mk'=>'Y','edittm'=>date('Y-m-d H:i:s')
                    ]);
                    $dev->save();
                }
                if($num) return getSuccessTip([
                    'title'=>'数据新增！',
                    'remark'=>'您刚刚新建了一个项目=》'.$data['pro_code'].'#'.$data['pro_name']
                ]);
                else return getFailureTip([
                    'title'=>'数据新增！',
                    'remark'=>'十分遗憾=》'.$data['pro_code'].'#'.$data['pro_name'].'数据新增失败！'
                ]);
            }
        }elseif($dataid == 'Pdev'){
            if(isset($data['pk'])){// 修改
                $map = ['no'=>$data['pk']];
                $num = $m->save($data,$map);                
                if($num) return getSuccessTip([
                    'title'=>'数据修改',
                    'remark'=>'您成功修改项目成员=》'.$data['name'].'#'
                ]);
                else return getFailureTip([
                    'title'=>'数据修改',
                    'remark'=>'十分遗憾，您本次的数据修改无效=》'.$data['name'].'#'
                ]);
            }else{
                $uInfo = $this->infoUser();
                $data['start_dt'] = date('Y-m-d H:i:s');
                $data['edittm'] = $data['start_dt'];
                $data['editor'] = $uInfo['user_name'];
                $data['founder_mk'] = 'N';
                if(empty($data['position'])) $data['position'] = '成员';
                $m->data($data);       
                $num = $m->save();
                if($num) return getSuccessTip([
                    'title'=>'数据新增！',
                    'remark'=>'您成功添加了项目成员=》'.$data['name'].'#'
                ]);
                else return getFailureTip([
                    'title'=>'数据新增！',
                    'remark'=>'十分遗憾，添加了项目成员=》'.$data['name'].'失败！'
                ]);
            }
        }
        debugOut($data,true);
    }
    /*****************************************************Ajax 数据处理***********************************************************************/
    public function ajax()
    {
        isset($_POST['item']) or die('非法请求地址');
        $item = $_POST['item'];
        $ret = '';
        switch($item){
            case 'index/logNo':
                $ret = $this->_getLogs($_POST['uid'],null,$_POST['no']);
                break;
            case 'index/DeletePrj':
                $uid = $_POST['uid'];
                $map = ['pro_code'=>$uid];
                // 开发者
                $Pdev = Loader::model('Pdev');
                $Pdev::destroy($map);
                // 项目日志
                $Plogs = Loader::model('Plogs');
                $Plogs::destroy($map);
                // 项目结构树
                $Ptree = Loader::model('Ptree');
                $Ptree::destroy($map);
                // 项目
                $Plist = Loader::model('Plist');
                $ret = $Plist::destroy($map);
                break;
        }
        return $ret;
    }
}
